package com.twm.drug.controller;

import com.twm.drug.common.ResultMapUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 用户相关的controller
 */
@Controller
public class UserController {
    /**
     * 转向登录页面
     */
    @RequestMapping(value = "/login") //访问login页面的时候，会跳转到/login的页面
    public String login(){
        return "/login";
    }

    /**
     * 判断用户是否登录成功
     */
    @RequestMapping(value = "/toLogin")
    @ResponseBody
    public Object toLogin(String username, String password){
        // 如果没有用户名或者密码
        if (username == null || password == null){
            return ResultMapUtils.getHashMapLogin("用户名和密码不能为空","2");
        }
        // 如果有用户名和密码
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            // 登录成功
            subject.login(token);
        }catch (UnknownAccountException e){ // 登录失败
            return ResultMapUtils.getHashMapLogin("用户名不存在","2");
        }catch (IncorrectCredentialsException e){
            return ResultMapUtils.getHashMapLogin("密码错误","2");
        }
        return ResultMapUtils.getHashMapLogin("验证成功", "1");
    }

    /**
     * 转向后台首页
     */
    @RequestMapping(value = "/index")
    public String index(){
        return "/index";
    }

    /**
     * 退出系统转向
     */
    @RequestMapping(value = "/logout")
    public String logout(){
//        清理登录的信息
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }
}
